<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document Title</title>
    <style>
        #app {
            width: 580px;
            margin: 0px auto;
        }

        table {
            width: 560px;
            border: 1px solid #ccc;
            border-collapse: collapse;
        }

        td {
            text-align: center;
        }

        input {
            width: 20px;
        }

        .numSpan {
            cursor: pointer;
        }
    </style>
</head>

<body>
<h1>计算属性实现统计购物车</h1>
<hr>

<div id="app">
    <table>
        <tr>
            <th>编号</th>
            <th>名称</th>
            <th>单价</th>
            <th>数量</th>
        </tr>
        <tr v-for="(item,index) in itemsList" :key="index">
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
            <td>{{item.price}}</td>
            <td><span class="numSpan" @click="sub(index)">-</span>
                <input type="text" name="number" v-model="item.num"/>
                <span class="numSpan" @click="add(index)">+</span>
            </td>
        </tr>
        <tr>
            <td colspan="4">总金额：{{totalPrice}} 元</td>
        </tr>
    </table>
</div>
<!--使用CDN方式引入vue-->
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.4/vue.min.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            itemsList: [
                {id: '001', name: '康师傅红烧牛肉面', price: 4, num: 10},
                {id: '002', name: '农夫山泉', price: 2, num: 5},
                {id: '003', name: '清风卫生纸', price: 10, num: 2},
                {id: '004', name: '洽洽瓜子', price: 12, num: 3}
            ]
        },
        computed: {
            //总价格计算属性
            totalPrice: function () {
                let total = 0;
                for (let i of this.itemsList) {
                    total += i.price * i.num;
                }
                return total;
            }
        },
        methods: {
            sub(index) {
                if (this.itemsList[index].num > 1) {
                    this.itemsList[index].num--;
                }
            },
            add(index) {
                if (this.itemsList[index].num < 100) {
                    this.itemsList[index].num++;
                }
            }
        }
    })
</script>
</body>
</html>

